import 'package:flutter/material.dart';

enum QuestionType {
  singleChoice,
  multipleChoice,
  fillBlank,
  trueOrFalse,
  shortAnswer,
}

class Choice {
  final String id;
  final String text;

  Choice({required this.id, required this.text});

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'text': text,
    };
  }

  factory Choice.fromJson(Map<String, dynamic> json) {
    return Choice(
      id: json['id'] ?? '',
      text: json['text'] ?? '',
    );
  }
}

abstract class Question {
  final String id;
  final String text;
  final int score;
  final QuestionType type;
  final String? analysis;

  Question({
    required this.id,
    required this.text,
    required this.score,
    required this.type,
    this.analysis,
  });

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'text': text,
      'score': score,
      'type': type.toString(),
      'analysis': analysis,
    };
  }

  // 静态工厂方法，根据类型创建对应的题目对象
  static Question? fromJson(Map<String, dynamic> json) {
    try {
      final typeString = json['type'] ?? '';
      final QuestionType type;
      
      // 解析题目类型
      if (typeString.contains('singleChoice')) {
        type = QuestionType.singleChoice;
      } else if (typeString.contains('multipleChoice')) {
        type = QuestionType.multipleChoice;
      } else if (typeString.contains('fillBlank')) {
        type = QuestionType.fillBlank;
      } else if (typeString.contains('trueOrFalse')) {
        type = QuestionType.trueOrFalse;
      } else if (typeString.contains('shortAnswer')) {
        type = QuestionType.shortAnswer;
      } else {
        return null;
      }

      final id = json['id'] ?? '';
      final text = json['text'] ?? '';
      final score = json['score'] ?? 0;
      final analysis = json['analysis'];

      switch (type) {
        case QuestionType.singleChoice:
          final choicesJson = json['choices'] as List? ?? [];
          final choices = choicesJson
              .map((c) => Choice.fromJson(c as Map<String, dynamic>))
              .toList();
          final correctOption = json['correctOption'] ?? 0;
          return SingleChoiceQuestion(
            id: id,
            text: text,
            score: score,
            choices: choices,
            correctOption: correctOption,
            analysis: analysis,
          );

        case QuestionType.multipleChoice:
          final choicesJson = json['choices'] as List? ?? [];
          final choices = choicesJson
              .map((c) => Choice.fromJson(c as Map<String, dynamic>))
              .toList();
          final correctOptionsJson = json['correctOptions'] as List? ?? [];
          final correctOptions = correctOptionsJson.map((o) => o as int).toList();
          return MultipleChoiceQuestion(
            id: id,
            text: text,
            score: score,
            choices: choices,
            correctOptions: correctOptions,
            analysis: analysis,
          );

        case QuestionType.fillBlank:
          final correctAnswer = json['correctAnswer'] ?? '';
          return FillBlankQuestion(
            id: id,
            text: text,
            score: score,
            correctAnswer: correctAnswer,
            analysis: analysis,
          );

        case QuestionType.trueOrFalse:
          final correctAnswer = json['correctAnswer'] ?? false;
          return TrueOrFalseQuestion(
            id: id,
            text: text,
            score: score,
            correctAnswer: correctAnswer,
            analysis: analysis,
          );

        case QuestionType.shortAnswer:
          final referencedAnswer = json['referencedAnswer'] ?? '';
          return ShortAnswerQuestion(
            id: id,
            text: text,
            score: score,
            referencedAnswer: referencedAnswer,
            analysis: analysis,
          );
      }
    } catch (e) {
      print('解析题目JSON失败: $e');
      return null;
    }
  }
}

abstract class ChoiceQuestion extends Question {
  final List<Choice> choices;
  
  ChoiceQuestion({
    required String id,
    required String text,
    required int score,
    required QuestionType type,
    required this.choices,
    String? analysis,
  }) : super(
          id: id,
          text: text,
          score: score,
          type: type,
          analysis: analysis,
        );
        
  List<String> get options => choices.map((c) => c.text).toList();
        
  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = super.toJson();
    json['choices'] = choices.map((c) => c.toJson()).toList();
    return json;
  }
}

class SingleChoiceQuestion extends ChoiceQuestion {
  final int correctOption;

  SingleChoiceQuestion({
    required String id,
    required String text,
    required int score,
    required List<Choice> choices,
    required this.correctOption,
    String? analysis,
  }) : super(
          id: id,
          text: text,
          score: score,
          type: QuestionType.singleChoice,
          choices: choices,
          analysis: analysis,
        );
        
  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = super.toJson();
    json['correctOption'] = correctOption;
    return json;
  }
}

class MultipleChoiceQuestion extends ChoiceQuestion {
  final List<int> correctOptions;

  MultipleChoiceQuestion({
    required String id,
    required String text,
    required int score,
    required List<Choice> choices,
    required this.correctOptions,
    String? analysis,
  }) : super(
          id: id,
          text: text,
          score: score,
          type: QuestionType.multipleChoice,
          choices: choices,
          analysis: analysis,
        );
        
  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = super.toJson();
    json['correctOptions'] = correctOptions;
    return json;
  }
}

class FillBlankQuestion extends Question {
  final String correctAnswer;
  final List<String> correctAnswers; // 支持多空填空
  final int blankCount; // 空的数量

  FillBlankQuestion({
    required String id,
    required String text,
    required int score,
    required this.correctAnswer,
    String? analysis,
  }) : correctAnswers = _parseCorrectAnswers(correctAnswer),
       blankCount = _parseCorrectAnswers(correctAnswer).length,
       super(
          id: id,
          text: text,
          score: score,
          type: QuestionType.fillBlank,
          analysis: analysis,
        );

  // 解析正确答案，支持中英文逗号
  static List<String> _parseCorrectAnswers(String correctAnswer) {
    // 检查是否包含逗号（中文或英文）
    final hasEnglishComma = correctAnswer.contains(',');
    final hasChineseComma = correctAnswer.contains('，');

    if (hasEnglishComma) {
      // 优先使用英文逗号分割
      return correctAnswer.split(',').map((e) => e.trim()).toList();
    } else if (hasChineseComma) {
      // 使用中文逗号分割
      return correctAnswer.split('，').map((e) => e.trim()).toList();
    } else {
      // 单空填空题
      return [correctAnswer.trim()];
    }
  }

  // 判断是否为多空填空题
  bool get isMultiBlank => blankCount > 1;

  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = super.toJson();
    json['correctAnswer'] = correctAnswer;
    json['correctAnswers'] = correctAnswers;
    json['blankCount'] = blankCount;
    return json;
  }
}

class TrueOrFalseQuestion extends Question {
  final bool correctAnswer;

  TrueOrFalseQuestion({
    required String id,
    required String text,
    required int score,
    required this.correctAnswer,
    String? analysis,
  }) : super(
          id: id,
          text: text,
          score: score,
          type: QuestionType.trueOrFalse,
          analysis: analysis,
        );
        
  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = super.toJson();
    json['correctAnswer'] = correctAnswer;
    return json;
  }
}

class ShortAnswerQuestion extends Question {
  final String referencedAnswer;

  ShortAnswerQuestion({
    required String id,
    required String text,
    required int score,
    required this.referencedAnswer,
    String? analysis,
  }) : super(
          id: id,
          text: text,
          score: score,
          type: QuestionType.shortAnswer,
          analysis: analysis,
        );
        
  @override
  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = super.toJson();
    json['referencedAnswer'] = referencedAnswer;
    return json;
  }
} 